package quotation.web.invite.service.impl;

import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.ObjectUtil;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import quotation.enums.TimeUnitEnum;
import quotation.web.invite.ddd.form.GenerateForm;
import quotation.web.invite.service.InviteService;

import java.security.SecureRandom;
import java.time.LocalDate;

/**
 * @author lyx
 * @date 2025/2/24
 */
@Slf4j
@Service
public class inviteServiceImpl implements InviteService {


    private static final String CHARACTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";

    private static final int INVITE_CODE_LENGTH = 6;

    private static final SecureRandom RANDOM = new SecureRandom();

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private RedissonClient redissonClient;

    @Override
    public String generate(GenerateForm form) {

        StringBuilder sb = new StringBuilder(INVITE_CODE_LENGTH);
        for (int i = 0; i < INVITE_CODE_LENGTH; i++) {
            int index = RANDOM.nextInt(CHARACTERS.length());
            sb.append(CHARACTERS.charAt(index));
        }
        String inviteCode = sb.toString();

        redisTemplate.opsForValue().set(inviteCode,
                form.getCount(),
                form.getExpire(),
                TimeUnitEnum.fromCode(form.getTimeUnit()).getTimeUnit());

        return inviteCode;
    }

    @Override
    public boolean validate(String inviteCode) {

        Object o = redisTemplate.opsForValue().get(inviteCode);

        if (ObjectUtil.isNull(o)) {
            return false;
        }
        Integer integer = Integer.valueOf(o.toString());

        if (integer.compareTo(0) < 0) {
            redisTemplate.delete(inviteCode);
            return false;
        }

        redisTemplate.opsForValue().decrement(inviteCode, 1);


        return true;
    }
}
